package cn.zmwh.manage.api.modules.umps.service;

import cn.hutool.core.util.StrUtil;
import cn.zmwh.common.security.base.BaseUserDetails;
import cn.zmwh.common.security.base.UserService;
import cn.zmwh.common.security.pojo.dto.LoginDTO;
import cn.zmwh.common.security.pojo.vo.WxDTO;
import cn.zmwh.manage.api.modules.umps.entity.UserWechat;
import cn.zmwh.manage.api.modules.umps.mapper.UserWechatMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author dmzmwh
 * @since 2025-03-18
 */
@Service
public class UserWechatService extends ServiceImpl<UserWechatMapper, UserWechat> {

    @Autowired
    UserService userService;

    /**
     * 查询微信用户
     *
     * @param openId
     * @param unionId
     * @param uType
     * @return
     */
    public UserWechat getByOpenId(String openId, String unionId, Integer uType) {

        UserWechat userWechat = baseMapper.selectOne(Wrappers.<UserWechat>lambdaQuery()
                .eq(StrUtil.isBlank(unionId), UserWechat::getOpenId, openId)
                .eq(StrUtil.isNotBlank(unionId), UserWechat::getUnionId, unionId)
                .eq(UserWechat::getUType, uType));
        return userWechat;
    }


    /**
     * 创建
     *
     * @param loginDTO
     * @return
     */
    public UserWechat saveAndUser(LoginDTO loginDTO) {
        WxDTO wxDTO = loginDTO.getWxDTO();
        BaseUserDetails userDetails = (BaseUserDetails) userService.loadUser(loginDTO);
        UserWechat userWechat = new UserWechat();
        userWechat.setOpenId(wxDTO.getOpenId());
        userWechat.setUnionId(wxDTO.getUnionId());
        userWechat.setUType(loginDTO.getUType());
        userWechat.setUid(userDetails.getId());
        userWechat.setCreateTime(new Date());
        baseMapper.insert(userWechat);
        return userWechat;
    }
}
